package com.ftg.learn.chapter03.config;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.Resource;

/**
 * @author kangjx
 * @createTime 2022/11/3
 */
@Configuration
@PropertySource("my.properties")
public class DataBaseConfig {

    @Resource
    MysqlDatasource mysqlDatasource;

    @Bean
    public SqlSession initSqlsessionFactory(){

        PooledDataSource pd = new PooledDataSource();
        pd.setDriver(mysqlDatasource.getDriverclass());
        pd.setUrl(mysqlDatasource.getUrl());
        pd.setUsername(mysqlDatasource.getUsername());
        pd.setPassword(mysqlDatasource.getPassowrd());

        //mybatis环境
        JdbcTransactionFactory jdbcTransaction = new JdbcTransactionFactory();
        Environment environment = new Environment("mysqldatasource",jdbcTransaction,pd);

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setEnvironment(environment);

        //基本设置
        config.setLogImpl(StdOutImpl.class);

        //添加sqlmapper
        config.addMappers("com.ftg.learn.chapter03.mapper");

        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(config);

        return sqlSessionFactory.openSession(true);
    }


}
